/*
 * Created by SharpDevelop.
 * User: michaelo
 * Date: 18/05/2005
 * Time: 19:08
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Orz.LogManager.Config;
using System.Collections;
using System.Text.RegularExpressions;

namespace Orz.LogManager
{
	/// <summary>
	/// Description of EditLogset.
	/// </summary>
	public class EditLogsetForm : System.Windows.Forms.Form
	{
		private System.ComponentModel.IContainer components;
		private System.Windows.Forms.Button cmdDeleteLogFile;
		private System.Windows.Forms.Button cmdNewLogFile;
		private System.Windows.Forms.GroupBox grpLogFiles;
		private System.Windows.Forms.ColumnHeader colName;
		private System.Windows.Forms.TextBox txtMaxCharsPerWindow;
		private System.Windows.Forms.Button cmdOK;
		private System.Windows.Forms.Button cmdCopy;
		private System.Windows.Forms.ListView lvwFiles;
		private System.Windows.Forms.Button cmdCancel;
		private System.Windows.Forms.TextBox txtFileName;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ColumnHeader colPath;
		private System.Windows.Forms.Button cmdEditLogFile;
		private System.Windows.Forms.TextBox txtDescription;
		private System.Windows.Forms.ImageList imageList1;
		
		
		private bool bWasCancelled_i;
		private LogsetWithFile working_i;
		private LogsetWithFile original_i;
		
		private HelpForm help_i;
		
		private const int IMG_LOCAL_FILE = 0;
		private const int IMG_TELNET_FILE = 1;
		private const int IMG_SSH_FILE = 2;
		
		
		
		private EditLogsetForm()
		{
			// Should never be called
		}
		
		
		
		
		public EditLogsetForm (LogsetWithFile set_p)
		{
			InitializeComponent();
			original_i = set_p;
			
			// Make a backup of the working set before we start
			working_i = LogsetLoader.CloneLogsetWithFile (original_i);
			
			help_i = new HelpForm (this);
			
			PopulateFields();
		}
		
		
		
		
		public bool WasCancelled
		{
			get { return bWasCancelled_i; }
		}
		
		
		
		
		private void PopulateFields ()
		{
			txtFileName.Text = working_i.FileName;
			txtDescription.Text = working_i.Logset.description;
			txtMaxCharsPerWindow.Text = working_i.Logset.maxCharsPerWindow;			
			PopulateListview();
		}
		
		
		private void PopulateListview()
		{
			lvwFiles.Items.Clear();
			
			IEnumerator files = working_i.Logset.logfile.GetEnumerator();
			
			while (files.MoveNext())
			{
				logsetLogfile file = (logsetLogfile) files.Current;
				
				int iIconIndex = IMG_LOCAL_FILE;
				
				if (LogsetLoader.isSSH(file))
				{
					iIconIndex = IMG_SSH_FILE;
				}
				else if (LogsetLoader.isTelnet(file))
				{
					iIconIndex = IMG_TELNET_FILE;
				}								
				
				ListViewItem item = lvwFiles.Items.Add(file.name, iIconIndex);
				
				string sPath = file.path;
				
				if (iIconIndex > 0)  // i.e. is telnet or ssh
				{
					sPath = file.telnetHost + " : " + sPath;
				}
				
				item.SubItems.Add(sPath);
			}
			
			if (lvwFiles.Items.Count > 0)
			{
				lvwFiles.SelectedItems.Clear();
				lvwFiles.Items[0].Selected = true;				
			}							
			
			UpdateButtons();
		}
		
		
		
		
		
		private bool DoSave()
		{
			// First make sure the filename is a valid one, i.e. that it
			// only contains a-z, 0-1, dots, underscores, and spaces.
			
			if (! IsValidFileName (txtFileName.Text))
			{
				MessageBox.Show("That is not a valid Windows filename!",
				                this.Text);
				
				return false;
			}
			
			
			if (! IsValidMaxChars (txtMaxCharsPerWindow.Text))
			{
				MessageBox.Show ("The maximum number of chars is nasty bad", this.Text);
				return false;
			}
			
			
			if (0 == lvwFiles.Items.Count)
			{
				MessageBox.Show("You need to specify at least one log file to view!\n" +
				                "Do this by clicking the 'New...' button and filling out the details on that form.",
				                this.Text);
				return false;
			}
			
			
			// Copy the values across
			working_i.FileName = AppendFileExtension(txtFileName.Text);
			working_i.Logset.description = txtDescription.Text;
			working_i.Logset.maxCharsPerWindow = txtMaxCharsPerWindow.Text;
			
			String sOriginalFileName = original_i.FileName;
			
			// Save the new logset
			LogsetLoader.SaveLogsetWithFile (working_i);
			
			// If this was an existing one that's been renamed then delete the old one
			if (null != sOriginalFileName  &&  sOriginalFileName.Length > 0  &&
			    !sOriginalFileName.Equals(working_i.FileName))
			{
				LogsetLoader.DeleteLogset(sOriginalFileName);
			}
			
			// Now copy the working logset details into the original one
			original_i.Logset = LogsetLoader.CloneLogset (working_i.Logset);
			original_i.FileName = working_i.FileName;
			
			MessageBox.Show ("Saved");
			
			return true;
		}
		
		
		
		private bool IsValidFileName (String sFileName_p)
		{
			try
			{
			  	new FileInfo(sFileName_p);
			  	return true;
			}
			catch (ArgumentException)
			{
				return false;
			}
			catch (System.IO.PathTooLongException)
			{
				return false;
			}
			catch (NotSupportedException)
			{
				return false;
			}			
		}
		
		
		private bool IsValidMaxChars (String sNumChars_p)
		{
			try
			{
				int iMaxChars = int.Parse(sNumChars_p);
				return iMaxChars > 0;
			}
			catch (Exception e)
			{
				return false;
			}
		}
		
		
		
		private string AppendFileExtension (String sFileName_p)
		{
			if (sFileName_p.EndsWith(".xml"))
			{
				return sFileName_p;
			}
			else
			{
				return sFileName_p + ".xml";
			}
		}
		
		
		
		private void UpdateButtons ()
		{
			bool isOnlyOneLogFileSelected = (1 == lvwFiles.SelectedItems.Count);
			bool isAtLeastOneLogFileSelected = (lvwFiles.SelectedItems.Count > 0);
						
			cmdEditLogFile.Enabled = isOnlyOneLogFileSelected;
			cmdDeleteLogFile.Enabled = isAtLeastOneLogFileSelected;
		}
		
		
		
		
		
		
		
		
		void CmdOKClick(object sender, System.EventArgs e)
		{
			if (DoSave())
			{
				bWasCancelled_i = false;
				this.Close();
			}
		}
		
		void CmdCancelClick(object sender, System.EventArgs e)
		{
			bWasCancelled_i = true;
			this.Close();
		}
		
		void CmdNewLogFileClick(object sender, System.EventArgs e)
		{
			logsetLogfile file = new logsetLogfile();
			
			
			if (lvwFiles.Items.Count > 0  &&  1 == lvwFiles.SelectedIndices.Count)
			{
				int iIndex = lvwFiles.SelectedIndices[0];
				logsetLogfile selected = (logsetLogfile) working_i.Logset.logfile[iIndex];
				
				if (DialogResult.Yes == MessageBox.Show ("Okey dokey!  Do you want to create a copy of the selected one (" + selected.name + ")?", "New log file reference", MessageBoxButtons.YesNo))
				{
					file = LogsetLoader.CloneLogfile(selected);
					file.name = null;
				}
			}
			
			
			EditLogFileForm f = new EditLogFileForm(file);
			f.ShowDialog();
			
			if (! f.WasCancelled)
			{
				AddNewLogfile(file);
			}
			
			PopulateListview();
		}
		
		
		private void AddNewLogfile(logsetLogfile file_p)
		{
			logsetLogfile[] origArray = working_i.Logset.logfile;
				
			logsetLogfile[] newArray = new logsetLogfile[origArray.Length+1];
			
			for (int i=0; i<origArray.Length; i++)
			{
				newArray[i] = origArray[i];
			}
			     
			newArray[newArray.Length-1] = file_p;
			
			working_i.Logset.logfile = newArray;
		}
		
		
		
		void CmdEditLogFileClick(object sender, System.EventArgs e)
		{
			if (0 == lvwFiles.Items.Count  ||  0 == lvwFiles.SelectedIndices.Count) return;
			
			int iIndex = lvwFiles.SelectedIndices[0];
			logsetLogfile file = working_i.Logset.logfile[iIndex];			
			
			EditLogFileForm f = new EditLogFileForm(file);
			f.ShowDialog();
			
			PopulateListview();
		}
		
		
		void LvwFilesDoubleClick(object sender, System.EventArgs e)
		{
			CmdEditLogFileClick(sender, e);
		}
		
		
		
		
		void CmdDeleteLogFileClick(object sender, System.EventArgs e)
		{
			if (0 == lvwFiles.Items.Count  ||  0 == lvwFiles.SelectedIndices.Count) return;
			
			string sConfirmationMessage = (lvwFiles.SelectedItems.Count > 1 ? 
			                               "Are you sure you want to remove these entries for multiple log files?\n" :
			                               "Are you sure you want to remove the entry for this log file?\n");
			
			IList logfilesToDelete = new ArrayList();
			
			foreach (ListViewItem item in lvwFiles.SelectedItems)
			{
				logsetLogfile file = working_i.Logset.logfile[item.Index];
				logfilesToDelete.Add(item.Index);
				sConfirmationMessage += "\n    " + file.name;
			}
			
			if (DialogResult.Yes == MessageBox.Show (sConfirmationMessage, this.Text, MessageBoxButtons.YesNo))
			{								
				logsetLogfile[] origArray = working_i.Logset.logfile;				
				logsetLogfile[] newArray = new logsetLogfile[origArray.Length-logfilesToDelete.Count];

				int iOrigArrayIndex = 0;
				int iNewArrayIndex = 0;
				
				for (iOrigArrayIndex=0; iOrigArrayIndex < origArray.Length; iOrigArrayIndex++)
				{
					if (!logfilesToDelete.Contains(iOrigArrayIndex))
					{
						newArray[iNewArrayIndex] = origArray[iOrigArrayIndex];
						iNewArrayIndex++;
					}					
				}
								
				working_i.Logset.logfile = newArray;
				
				PopulateListview();
			}
		}
		
		
		
		
		
		#region Windows Forms Designer generated code
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent() {
			this.components = new System.ComponentModel.Container();
			System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditLogsetForm));
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.txtDescription = new System.Windows.Forms.TextBox();
			this.cmdEditLogFile = new System.Windows.Forms.Button();
			this.colPath = new System.Windows.Forms.ColumnHeader();
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.txtFileName = new System.Windows.Forms.TextBox();
			this.cmdCancel = new System.Windows.Forms.Button();
			this.lvwFiles = new System.Windows.Forms.ListView();
			this.colName = new System.Windows.Forms.ColumnHeader();
			this.cmdCopy = new System.Windows.Forms.Button();
			this.cmdOK = new System.Windows.Forms.Button();
			this.txtMaxCharsPerWindow = new System.Windows.Forms.TextBox();
			this.grpLogFiles = new System.Windows.Forms.GroupBox();
			this.cmdNewLogFile = new System.Windows.Forms.Button();
			this.cmdDeleteLogFile = new System.Windows.Forms.Button();
			this.grpLogFiles.SuspendLayout();
			this.SuspendLayout();
			// 
			// imageList1
			// 
			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
			this.imageList1.Images.SetKeyName(0, "local.png");
			this.imageList1.Images.SetKeyName(1, "network.png");
			this.imageList1.Images.SetKeyName(2, "secure2.png");
			// 
			// txtDescription
			// 
			this.txtDescription.Location = new System.Drawing.Point(160, 64);
			this.txtDescription.Name = "txtDescription";
			this.txtDescription.Size = new System.Drawing.Size(296, 20);
			this.txtDescription.TabIndex = 2;
			this.txtDescription.Tag = "An optional description of this configuration file, to help you keep track of whi" +
			"ch is which!";
			// 
			// cmdEditLogFile
			// 
			this.cmdEditLogFile.Location = new System.Drawing.Point(264, 216);
			this.cmdEditLogFile.Name = "cmdEditLogFile";
			this.cmdEditLogFile.Size = new System.Drawing.Size(75, 24);
			this.cmdEditLogFile.TabIndex = 10;
			this.cmdEditLogFile.Tag = "Displays details of the selected log file and lets you make changes to it.";
			this.cmdEditLogFile.Text = "&Edit...";
			this.cmdEditLogFile.Click += new System.EventHandler(this.CmdEditLogFileClick);
			// 
			// colPath
			// 
			this.colPath.Text = "Path";
			this.colPath.Width = 400;
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(16, 32);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(136, 16);
			this.label1.TabIndex = 0;
			this.label1.Tag = "The XML file name used to store this configuration.  It should be relative to the" +
			" Log Manager installation folder, and must be unique for each different configur" +
			"ation.";
			this.label1.Text = "Configuration filename:";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(16, 64);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(100, 16);
			this.label2.TabIndex = 0;
			this.label2.Tag = "An optional description of this configuration file, to help you keep track of whi" +
			"ch is which!";
			this.label2.Text = "Description:";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(16, 96);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(144, 16);
			this.label3.TabIndex = 0;
			this.label3.Tag = resources.GetString("label3.Tag");
			this.label3.Text = "Max size per window (KB):";
			// 
			// txtFileName
			// 
			this.txtFileName.Location = new System.Drawing.Point(160, 32);
			this.txtFileName.Name = "txtFileName";
			this.txtFileName.Size = new System.Drawing.Size(296, 20);
			this.txtFileName.TabIndex = 1;
			this.txtFileName.Tag = resources.GetString("txtFileName.Tag");
			// 
			// cmdCancel
			// 
			this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.cmdCancel.Location = new System.Drawing.Point(472, 48);
			this.cmdCancel.Name = "cmdCancel";
			this.cmdCancel.Size = new System.Drawing.Size(80, 24);
			this.cmdCancel.TabIndex = 6;
			this.cmdCancel.Tag = "Closes the dialog box, undoing any changes you may have made.";
			this.cmdCancel.Text = "&Cancel";
			this.cmdCancel.Click += new System.EventHandler(this.CmdCancelClick);
			// 
			// lvwFiles
			// 
			this.lvwFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
									this.colName,
									this.colPath});
			this.lvwFiles.FullRowSelect = true;
			this.lvwFiles.HideSelection = false;
			this.lvwFiles.Location = new System.Drawing.Point(16, 24);
			this.lvwFiles.Name = "lvwFiles";
			this.lvwFiles.Size = new System.Drawing.Size(408, 184);
			this.lvwFiles.SmallImageList = this.imageList1;
			this.lvwFiles.TabIndex = 7;
			this.lvwFiles.Tag = "This list shows all the different log files that will be displayed as part of thi" +
			"s configuration.  Use the \'New\', \'Edit\' and \'Delete\' buttons below to change the" +
			"se.";
			this.lvwFiles.UseCompatibleStateImageBehavior = false;
			this.lvwFiles.View = System.Windows.Forms.View.Details;
			this.lvwFiles.SelectedIndexChanged += new System.EventHandler(this.LvwFilesSelectedIndexChanged);
			this.lvwFiles.DoubleClick += new System.EventHandler(this.LvwFilesDoubleClick);
			// 
			// colName
			// 
			this.colName.Text = "Name";
			this.colName.Width = 170;
			// 
			// cmdCopy
			// 
			this.cmdCopy.Location = new System.Drawing.Point(472, 112);
			this.cmdCopy.Name = "cmdCopy";
			this.cmdCopy.Size = new System.Drawing.Size(80, 24);
			this.cmdCopy.TabIndex = 8;
			this.cmdCopy.Text = "Copy from...";
			this.cmdCopy.Click += new System.EventHandler(this.CmdCopyClick);
			// 
			// cmdOK
			// 
			this.cmdOK.Location = new System.Drawing.Point(472, 16);
			this.cmdOK.Name = "cmdOK";
			this.cmdOK.Size = new System.Drawing.Size(80, 24);
			this.cmdOK.TabIndex = 6;
			this.cmdOK.Tag = "Closes the dialog box and saves any changes you have made.";
			this.cmdOK.Text = "&OK";
			this.cmdOK.Click += new System.EventHandler(this.CmdOKClick);
			// 
			// txtMaxCharsPerWindow
			// 
			this.txtMaxCharsPerWindow.Location = new System.Drawing.Point(160, 96);
			this.txtMaxCharsPerWindow.Name = "txtMaxCharsPerWindow";
			this.txtMaxCharsPerWindow.Size = new System.Drawing.Size(296, 20);
			this.txtMaxCharsPerWindow.TabIndex = 3;
			this.txtMaxCharsPerWindow.Tag = resources.GetString("txtMaxCharsPerWindow.Tag");
			// 
			// grpLogFiles
			// 
			this.grpLogFiles.Controls.Add(this.lvwFiles);
			this.grpLogFiles.Controls.Add(this.cmdNewLogFile);
			this.grpLogFiles.Controls.Add(this.cmdEditLogFile);
			this.grpLogFiles.Controls.Add(this.cmdDeleteLogFile);
			this.grpLogFiles.Location = new System.Drawing.Point(16, 136);
			this.grpLogFiles.Name = "grpLogFiles";
			this.grpLogFiles.Size = new System.Drawing.Size(440, 256);
			this.grpLogFiles.TabIndex = 7;
			this.grpLogFiles.TabStop = false;
			this.grpLogFiles.Text = "Individual log files to be displayed";
			// 
			// cmdNewLogFile
			// 
			this.cmdNewLogFile.Location = new System.Drawing.Point(184, 216);
			this.cmdNewLogFile.Name = "cmdNewLogFile";
			this.cmdNewLogFile.Size = new System.Drawing.Size(75, 24);
			this.cmdNewLogFile.TabIndex = 11;
			this.cmdNewLogFile.Tag = "Allows you to associate a new log file with this configuration.";
			this.cmdNewLogFile.Text = "&Add...";
			this.cmdNewLogFile.Click += new System.EventHandler(this.CmdNewLogFileClick);
			// 
			// cmdDeleteLogFile
			// 
			this.cmdDeleteLogFile.Location = new System.Drawing.Point(344, 216);
			this.cmdDeleteLogFile.Name = "cmdDeleteLogFile";
			this.cmdDeleteLogFile.Size = new System.Drawing.Size(75, 24);
			this.cmdDeleteLogFile.TabIndex = 9;
			this.cmdDeleteLogFile.Tag = "Removes the selected log file\'s details from this configuration so that it will n" +
			"o longer be displayed.";
			this.cmdDeleteLogFile.Text = "&Delete...";
			this.cmdDeleteLogFile.Click += new System.EventHandler(this.CmdDeleteLogFileClick);
			// 
			// EditLogsetForm
			// 
			this.AcceptButton = this.cmdOK;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.cmdCancel;
			this.ClientSize = new System.Drawing.Size(562, 400);
			this.Controls.Add(this.cmdCopy);
			this.Controls.Add(this.grpLogFiles);
			this.Controls.Add(this.cmdOK);
			this.Controls.Add(this.txtMaxCharsPerWindow);
			this.Controls.Add(this.txtDescription);
			this.Controls.Add(this.txtFileName);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.cmdCancel);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "EditLogsetForm";
			this.ShowInTaskbar = false;
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
			this.Text = "Log Configuration Properties";
			this.grpLogFiles.ResumeLayout(false);
			this.ResumeLayout(false);
			this.PerformLayout();
		}
		#endregion
		
		
		void CmdCopyClick(object sender, System.EventArgs e)
		{
			ImportLogFileForm f = new ImportLogFileForm();
			f.ShowDialog();
			
			if (null != f.LogFile)
			{
			 	logsetLogfile file = LogsetLoader.CloneLogfile(f.LogFile);
			 	AddNewLogfile(file);
			 	PopulateListview();
			}
		}
		
		void LvwFilesSelectedIndexChanged(object sender, System.EventArgs e)
		{
			UpdateButtons();
		}
		
	}
}
